package com.example.woke;

import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.bean.BaseResponse;
import com.bean.HuiKaAreaCode;
import com.bean.HuiKaBankBranchCode;
import com.bean.IndustryCategories;
import com.http.HttpMethods;
import com.jakewharton.rxbinding2.view.RxView;
import com.woke.adapter.OnItemClickListener;
import com.woke.fragment.HuiKaBankBranchDialogFragment;
import com.woke.fragment.HuiKaProvincesAndCitiesDialogFragment;
import com.woke.method.MyApp;
import com.woke.method.NetworkUtils;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.BR;
import com.zhongcai.online.R;
import com.zhongcai.online.databinding.ActivityHuiKaMerchantsInBinding;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.xl.xxl.tools.CommonUtil;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * 广州汇卡 商户入驻
 */
public class HuiKaMerchantsInActivity extends AppCompatActivity {

    private Handler mHandle = new Handler();
    private ActivityHuiKaMerchantsInBinding mBinding;
    private MyApp myApp;
    private int pageInde = 0;
    private HuiKaProvincesAndCitiesDialogFragment mProvincesAndCitiesDialogFragment;//省市
    private HuiKaBankBranchCode mBankBranchCode;  //所选开户支行
    private HuiKaAreaCode mMerchantsProvince, mMerchantsCity;//省市
    private HuiKaBankBranchDialogFragment mBranchDialogFragment;
    private int mChannelWay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//		setContentView (R.layout.activity_merchants_in);
        Intent intent = getIntent();
        mChannelWay = intent.getIntExtra("way", -1);

        myApp = MyApp.getInstance();
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_hui_ka_merchants_in);
        mBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pageInde > 1) {
                    mBinding.secondViewSwitcher.showPrevious();
                    pageInde--;
                } else if (pageInde > 0) {
                    mBinding.viewSwitcher.showPrevious();
                    pageInde--;
                } else {
                    finish();
                }
            }
        });
        mBinding.setVariable(BR.base_list_title, getResources().getString(R.string.title_activity_huika_merchants_in));

        initData();
        final String[] mIndustrIdValues = getResources().getStringArray(R.array.pu_fa_business_type);
        ArrayAdapter mBusinessTypedapter = new ArrayAdapter<String>(this, R.layout.spinner_item, R.id.textView, mIndustrIdValues);
        mBusinessTypedapter.setDropDownViewResource(R.layout.spinner_item_drop);


        RxView.clicks(mBinding.provincesAndCitiesTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //商户省市  选择行省市
                chooseProvincesAndCities();
            }
        });

        RxView.clicks(mBinding.bankNameTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //选择开户支行
                chooseBankBranch();
            }
        });

        RxView.clicks(mBinding.nextBtn).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //下一步
                String merchantName = mBinding.merchantNameEd.getText().toString();//商户名称
                String merchantShortName = mBinding.merchantShortNameEd.getText().toString();//商户简称
                String merchantAddress = mBinding.merchantAddressEd.getText().toString();//商户地址
                if (TextUtils.isEmpty(merchantName)) {
                    showToast(getResources().getString(R.string.hint_merchants_name));
                    return;
                }
                if (TextUtils.isEmpty(merchantShortName)) {
                    showToast(getResources().getString(R.string.hint_merchants_short_name2));
                    return;
                }

                if (mMerchantsProvince == null && mMerchantsCity == null) {
                    showToast(getResources().getString(R.string.hint_selecte_business_provinces));
                    return;
                }
                if (TextUtils.isEmpty(merchantAddress)) {
                    showToast(getResources().getString(R.string.hint_merchants_address));
                    return;
                }
                if (!NetworkUtils.isConnected(HuiKaMerchantsInActivity.this)) {
                    showToast(getResources().getString(R.string.error_net2));
                    return;
                }
                pageInde++;
                mBinding.viewSwitcher.showNext();
            }
        });
        RxView.clicks(mBinding.middleNextBtn).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //下一步

                String legalPersonName = mBinding.enterpriseLegalPersonEd.getText().toString();//企业法人

                String legalPersonPhone = mBinding.merchantContactPhoneEd.getText().toString();//法人手机
                String legalPersonidCard = mBinding.principalIdcardEd.getText().toString();//法人身份证

                if (TextUtils.isEmpty(legalPersonName)) {
                    showToast(getResources().getString(R.string.hint_enterprise_legal_person_name));
                    return;
                }


                if (!CommonUtil.isPhoneNo(legalPersonPhone)) {
                    showToast(getResources().getString(R.string.hint_phone_not_null));
                    return;
                }
                if (TextUtils.isEmpty(legalPersonidCard) || legalPersonidCard.length() < 14) {
                    showToast(getResources().getString(R.string.hint_id_card_length));
                    return;
                }

                if (!NetworkUtils.isConnected(HuiKaMerchantsInActivity.this)) {
                    showToast(getResources().getString(R.string.error_net2));
                    return;
                }
                pageInde++;
                mBinding.secondViewSwitcher.showNext();
            }
        });
        RxView.clicks(mBinding.commitBtn).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                //提交商户入驻信息

                String bankAccout = mBinding.merchantsBankAccountEd.getText().toString();    //银行卡号
                String bankCardHolderName = mBinding.merchantsBankAccountNameEd.getText().toString();  //持卡人姓名

                if (TextUtils.isEmpty(bankAccout)) {
                    showToast(getResources().getString(R.string.hint_merchants_bank_account));
                    return;
                }

                if (TextUtils.isEmpty(bankCardHolderName)) {
                    showToast(getResources().getString(R.string.hint_merchants_bank_account_name));
                    return;
                }

                if (mBankBranchCode == null) {
                    //开户支行
                    showToast(getResources().getString(R.string.hint_bank_name_select));
                    return;
                }

                if (!NetworkUtils.isConnected(HuiKaMerchantsInActivity.this)) {
                    showToast(getResources().getString(R.string.error_net2));
                    return;
                }

//                if(mChannelWay==-1){
//                    showToast(getResources().getString(R.string.error_net2));
//                    return;
//                }
                String merchantName = mBinding.merchantNameEd.getText().toString();//商户名称
                String merchantShortName = mBinding.merchantShortNameEd.getText().toString();//商户简称
                String merchantAddress = mBinding.merchantAddressEd.getText().toString();//商户地址


                String legalPersonName = mBinding.enterpriseLegalPersonEd.getText().toString();//企业法人
                String legalPersonPhone = mBinding.merchantContactPhoneEd.getText().toString();//法人手机
                String legalPersonidCard = mBinding.principalIdcardEd.getText().toString();//法人身份证


                Datas_load load = myApp.getDatas_load();
                if (load != null) {
                    String userId = load.getId();
                    if (!TextUtils.isEmpty(userId) && userId.matches("[0-9]*")) {

                        Map<String, String> params = new HashMap<>();
                        params.put("userId", userId);
                        params.put("way", String.valueOf(mChannelWay));
                        params.put("merName", merchantName);
                        params.put("merNameShort", merchantShortName);

                        params.put("provinceNo", mMerchantsCity.getP_code());
                        params.put("posAreaCode", mMerchantsCity.getAreacode());
                        params.put("merAddress", merchantAddress);

                        params.put("merLegalName", legalPersonName);
                        params.put("merLegalMobilePhone", legalPersonPhone);
                        params.put("merLegalNo", legalPersonidCard);


                        params.put("mbiAccountNo", bankAccout);
                        params.put("mbiAccountUser", bankCardHolderName);

                        params.put("bankPid", mBankBranchCode.getBankpid());    //开户总行
                        params.put("mbiBankNo", mBankBranchCode.getBankid());  //开户行银行行号
                        params.put("mbiBankName", mBankBranchCode.getBankname());  //开户银行名称
                        HttpMethods.getInstance().huiKaiMerchantsEnter(mCommitObserver, params);
                    }
                }


            }
        });
    }

    private void initData() {
        Datas_load load = MyApp.getInstance().getDatas_load();
        if (load != null) {
            //联系人电话号码
            mBinding.merchantContactPhoneEd.setText(load.getUser_login());

            //身份证号
            if (!TextUtils.isEmpty(load.getUser_no()) && load.getUser_no().length() >= 15) {
                mBinding.principalIdcardEd.setText(load.getUser_no());
            }
//            if(){}
            //银行卡卡号
            mBinding.merchantsBankAccountEd.setText(load.getCard_no());
            //开户行
//            mBinding.bankNameEd.setText(load.getBank_name());
        }
//        UserInfo userInfo = mRealm.where(UserInfo.class)
//                .equalTo("id", getLocalUserId(this))
//                .findFirst();
//        if (userInfo != null) {
//            //联系人电话号码
//            mBinding.merchantContactPhoneEd.setText(userInfo.getUser_login());
//            //身份证号
//            mBinding.merchantIdcardEd.setText(userInfo.getUser_no());
//            //银行卡卡号
//            mBinding.merchantsBankAccountEd.setText(userInfo.getCard_no());
//            //开户行
//            mBinding.bankNameEd.setText(userInfo.getBank_name());
//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (pageInde > 1) {
                mBinding.secondViewSwitcher.showPrevious();
                pageInde--;
                return false;
            } else if (pageInde > 0) {
                mBinding.viewSwitcher.showPrevious();
                pageInde--;
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);

    }


    /**
     * 选择省市
     */
    private void chooseProvincesAndCities() {
        if (NetworkUtils.isConnected(this)) {
            if (mProvincesAndCitiesDialogFragment == null) {
                mProvincesAndCitiesDialogFragment = new HuiKaProvincesAndCitiesDialogFragment();
                mProvincesAndCitiesDialogFragment.setOnItemClickListener(mItemClickListener);
            }
            mProvincesAndCitiesDialogFragment.show(getSupportFragmentManager(), "ProvincesAndCities");
        } else {
            showToast(getResources().getString(R.string.error_net2));
        }
    }

    /**
     * 选择支行
     */
    private void chooseBankBranch() {
        if (mBranchDialogFragment == null) {
            mBranchDialogFragment = new HuiKaBankBranchDialogFragment();
            mBranchDialogFragment.setOnItemClickListener(mItemClickListener);
        }
        mBranchDialogFragment.show(getSupportFragmentManager(), "BranchDialogFragment");
    }

    private OnItemClickListener mItemClickListener = new OnItemClickListener() {

        @Override
        public void OnItemClick(View view, int position) {

        }

        @Override
        public void OnItemClick(View view, Object object, int position) {
            if (object instanceof IndustryCategories) {
                //行业类别


            } else if (object instanceof HuiKaAreaCode) {
                HuiKaAreaCode areaCode = (HuiKaAreaCode) object;

                //商户所在省市
                if (areaCode.isProvinceCode()) {
                    //省
                } else {
                    //市
                    if (mProvincesAndCitiesDialogFragment != null) {
                        mMerchantsProvince = mProvincesAndCitiesDialogFragment.getProvinceAreaCode();
                        mMerchantsCity = mProvincesAndCitiesDialogFragment.getCityAreaCode();
                        String tempStr = mMerchantsProvince.getName() + mMerchantsCity.getName();
                        mBinding.provincesAndCitiesTv.setText(tempStr);
                    }
                }

            } else if (object instanceof HuiKaBankBranchCode) {
                mBankBranchCode = (HuiKaBankBranchCode) object;
                mBinding.bankNameTv.setText(mBankBranchCode.getBankname());
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private Observer<BaseResponse> mCommitObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {
            if (value != null) {
                if (value.resultSuccess()) {
                    new AlertDialog.Builder(HuiKaMerchantsInActivity.this).setTitle("提交成功").setMessage(value.getInfo()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            EventBus.getDefault().post(mChannelWay);
                            finish();
                        }
                    }).create().show();
                } else {
                    showToast(value.getInfo());
                }
            }
        }

        @Override
        public void onError(Throwable e) {
            if (e != null) {
                showToast(e.getMessage());
            }
        }

        @Override
        public void onComplete() {

        }
    };

}
